<?php

declare(strict_types=1);

namespace App\Middleware\Api;

use Hyperf\HttpServer\Contract\RequestInterface;
// use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\Context\Context;
use App\Constants\Status;
use App\Common\RedisCache;
use Psr\Container\ContainerInterface;
use App\Exception\ApiException;
use App\Service\DataResource;

class WaiMaiMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var RequestInterface
     */
    protected $request;

    public function __construct(ContainerInterface $container, RequestInterface $request)
    {
        $this->container = $container;
        $this->request = $request;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: POST, GET");
        header('Access-Control-Allow-Headers:Token,UserId');
        $path = $this->request->path();
        if ($path === '/favicon.ico') {
            unset($path);
            throw new ApiException(Status::INVALID_API);
        }
        if ($path === '/') {
            unset($path);
            throw new ApiException(Status::INVALID_API);
        }
        $data = $this->request->all();
        $UserId = $this->request->header('UserId');
        // 必须有apkey
        if (empty($UserId)) {
            throw new ApiException(Status::CODE_FORBIDDEN, 'UserId is null');
        }
        $this->checkUserInfoFormUserId($UserId);
        if ($data['_t'] > (time() + 300) || $data['_t'] < (time() - 300)) {
            throw new ApiException(Status::CODE_FORBIDDEN, 'Illegal request');
        }
        return $handler->handle($request);
    }
    /**
     * userId真实性验证
     * @param string $appkey
     * @author QianLong <87498106@qq.com>
     * @version 1.0.0
     */
    public function checkUserInfoFormUserId(string $UserId)
    {
        $redisCacheObj = new RedisCache();
        $getUserSettingData = $redisCacheObj->getUserInfoByUserId($UserId);
        unset($redisCacheObj);
        if (empty($getUserSettingData)) {
            throw new ApiException(Status::ILLEGAL_MUST_DATA_WMCPS);
        }
        // if ($getUserSettingData['fee_end_time'] < time()) {
        //     throw new ApiException(Status::CODE_FAIL, '用户已过期，请登录平台续费后使用：http://ecapi.cn');
        // }
        Context::set('cps_userInfo', $getUserSettingData);
        unset($getUserSettingData);
    }

    /**
     * 会员级别权限验证
     * @param $u_id
     * @param string $path
     */
    public function checkUserRank(string $path)
    {
        $redisCacheObj = new RedisCache();
        $uid = Context::get('uid');
        $userInfo = $redisCacheObj->getUserInfoById($uid);
        unset($uid);
        if (empty($userInfo)) {
            unset($redisCacheObj, $path);
            throw new ApiException(Status::USER_INFO_ERROR);
        }
        if ($userInfo['status'] != 1) {
            unset($redisCacheObj, $path);
            throw new ApiException(Status::USER_STATUS_ERROR);
        }
        $apiInfo = $redisCacheObj->getApiInfoByPath($path);
        unset($redisCacheObj, $path);
        if (empty($apiInfo)) {
            throw new ApiException(Status::INVALID_API);
        }
        if ($userInfo['fee_end_time'] < time()) {
            $userInfo['user_rank'] = 1;
        }
        if ($apiInfo['rank_group'] == 2 && $userInfo['user_rank'] == 1) {
            unset($apiInfo);
            throw new ApiException(Status::NO_ACCESS);
        }
        Context::set('userInfo', $userInfo);
        unset($userInfo, $apiInfo);
    }
    /**
     * 读取系统设置
     */
    public function getPlatFormSetting()
    {
        // 从缓存拿 没有就从数据库读取 初始化
        $redisCache = new RedisCache();
        $settingInfo = $redisCache->getPlatformSetting();
        unset($redisCache);
        if (!empty($settingInfo)) {
            Context::set('platSetting', $settingInfo);
            unset($settingInfo);
        } else {
            throw new ApiException(Status::NULL_SYSTEM_SETTING);
        }
    }
}
